package com.atguigu.java.ai.langchain4j.config;

import com.atguigu.java.ai.langchain4j.store.MongoChatMemoryStore;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.ClassPathDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: Mikey
 * @Date: 2025/9/4 14:59
 * @Description:
 **/
@Configuration
public class XiaozhiAgentConfig {

    @Resource
    private MongoChatMemoryStore mongoChatMemoryStore;

    @Bean
    ChatMemoryProvider chatMemoryProviderXiaozhi(){
        //使用lambda表达式简化匿名内部类
        return memoryId ->
                MessageWindowChatMemory.builder()
                        .id(memoryId)
                        .chatMemoryStore(mongoChatMemoryStore)
                        .maxMessages(20)
                        .build();
    }



    @Bean
    ContentRetriever contentRetrieverXiaozhi(){
        //加载需要的文档
        Document document1 = ClassPathDocumentLoader.loadDocument("医院信息.md");
        Document document2 = ClassPathDocumentLoader.loadDocument("科室信息.md");
        Document document3 = ClassPathDocumentLoader.loadDocument("神经内科.md");
        List<Document> documents = Arrays.asList(document1, document2, document3);

        //使用内存向量存储
        InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();

        //使用默认的文档分割器
        EmbeddingStoreIngestor.ingest(documents,embeddingStore);

        //从嵌入存储（EmbeddingStore）里检索和查询内容相关的向量
        return EmbeddingStoreContentRetriever.from(embeddingStore);

    }

    @Resource
    private EmbeddingStore embeddingStore;

    @Resource
    private EmbeddingModel embeddingModel;

    @Bean
    ContentRetriever contentRetrieverXiaozhiPincone(){

        //创建一个EmbeddingStoreContentRetriever对象 用于从嵌入存储中检索内容
        return EmbeddingStoreContentRetriever.builder()
                .embeddingModel(embeddingModel)//设置用于生成向量的嵌入模型
                .embeddingStore(embeddingStore)//指定需要使用的嵌入存储
                .maxResults(1)//返回匹配度最高的一条
                .minScore(0.8)//返回的结果相似分数不能小于0.8
                .build();
    }
}
